package cn.util.aliyun;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.lang.StringUtils;
import org.apache.http.entity.ContentType;
import org.apache.ibatis.logging.Log;
import org.apache.ibatis.logging.LogFactory;
import org.junit.Test;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * 阿里云OSS对象存储
 *
 * @author YuanDuDu
 */
@Component("aliyunOSSClientUtil")
public class AliyunOSSClientUtil {
    static Log log = LogFactory.getLog(AliyunOSSClientUtil.class);
    //阿里云API的外网域名
    public static String endpoint = "xxxx";
    //阿里云API的密钥Access Key ID
    public static String accessKeyId = "xxxx";
    //阿里云API的密钥Access Key Secret
    public static String accessKeySecret = "xxxx";
    //阿里云API的bucket名称
    public static String bucketName = "xxxx";
    //上传目录
    public static String filedir = "xxxx";

    //当前上传目录
    public static String path = "xxxx";


    private static OSSClient ossClient;

    public AliyunOSSClientUtil() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 获取连接
     */
    private static void init() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 关闭
     */
    private void destory() {
        ossClient.shutdown();
    }

    /**
     * 上传图片
     *
     * @param url
     */
    private static void uploadImg2Oss(String url) {
        File fileOnServer = new File(url);
        FileInputStream fin;
        try {
            fin = new FileInputStream(fileOnServer);
            String[] split = url.split("/");
            uploadFile2OSS(fin, split[split.length - 1]);
        } catch (FileNotFoundException e) {
            System.out.println("图片上传失败");
        }
    }


    private static String uploadImg2Oss(MultipartFile file) {
        if (file.getSize() > 1024 * 1024) {
            System.out.println("上传图片大小不能超过1M！");
        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try {
            InputStream inputStream = file.getInputStream();
            uploadFile2OSS(inputStream, name);
            return name;
        } catch (Exception e) {
            System.out.println("图片上传失败");
        }
        return null;
    }


    /**
     * 获得图片路径
     *
     * @param fileUrl
     * @return
     */
    private static String getImgUrl(String fileUrl) {
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            return getUrl(filedir+path + split[split.length - 1]);
        }
        return null;
    }

    /**
     * 上传到OSS服务器  如果同名文件会覆盖服务器上的
     *
     * @param instream 文件流
     * @param fileName 文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    private static String uploadFile2OSS(InputStream instream, String fileName) {
        String ret = "";
        try {
            //创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            //上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName, filedir+path + fileName, instream, objectMetadata);
            ret = putResult.getETag();
        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } finally {
            try {
                if (instream != null) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param FilenameExtension 文件后缀
     * @return String
     */
    private static String getcontentType(String FilenameExtension) {
        if (FilenameExtension.equalsIgnoreCase(".bmp")) {
            return "image/bmp";
        }
        if (FilenameExtension.equalsIgnoreCase(".gif")) {
            return "image/gif";
        }
        if (FilenameExtension.equalsIgnoreCase(".jpeg") ||
                FilenameExtension.equalsIgnoreCase(".jpg") ||
                FilenameExtension.equalsIgnoreCase(".png")) {
            return "image/jpeg";
        }
        if (FilenameExtension.equalsIgnoreCase(".html")) {
            return "text/html";
        }
        if (FilenameExtension.equalsIgnoreCase(".txt")) {
            return "text/plain";
        }
        if (FilenameExtension.equalsIgnoreCase(".vsd")) {
            return "application/vnd.visio";
        }
        if (FilenameExtension.equalsIgnoreCase(".pptx") ||
                FilenameExtension.equalsIgnoreCase(".ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (FilenameExtension.equalsIgnoreCase(".docx") ||
                FilenameExtension.equalsIgnoreCase(".doc")) {
            return "application/msword";
        }
        if (FilenameExtension.equalsIgnoreCase(".xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    private static String getUrl(String key) {
        // 设置URL过期时间为10年 3600l* 1000*24*365*10
        Date expiration = new Date(new Date().getTime() + 3600l * 1000 * 24 * 365 * 100);
        // 生成URL
        URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        if (url != null) {
            return url.toString();
        }
        return null;
    }

    private static String updateHead(MultipartFile file, long userId) throws IOException{
        if (file == null || file.getSize() <= 0) {
            System.out.println("没图片");
        }
        String name = uploadImg2Oss(file);
        String imgUrl = getImgUrl(name);

        return imgUrl;

    }

    /**
     * @param fileStream  百度富文本文件
     * @param file  普通File文件
     * @param zpath 保存在服务器上的路径
     * @param type  1图片类型 2文件类型
     * @return
     */
    @Test
    public static Map<String,Object> UploadOSS(FileItemStream fileStream,MultipartFile file, String zpath,int type){
        Map<String,Object> map= new HashMap<>();
        init();
        if(type==1){
            path= zpath;
        }
        //pdfFile = new File("D:\\66.jpg");
        FileInputStream fileInputStream = null;
        MultipartFile multipartFile=null;
        try {
            if(file!=null){

                multipartFile = file;
            }else{
                //百度富文本保存
                multipartFile = new MockMultipartFile(fileStream.getName(), fileStream.getName(),
                        ContentType.APPLICATION_OCTET_STREAM.toString(),  fileStream.openStream());
            }
            String dataurl=updateHead(multipartFile,1);
            dataurl=dataurl.substring(0,dataurl.indexOf("?"));
            if(type==1){
                map.put("imageurl",dataurl+"?x-oss-process=style/shuiyin");
                return map;
            }else {
                map.put("imageurl",dataurl);
                return map;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}